package com.pet.platform.service.impl;

import com.pet.platform.common.PageResult;
import com.pet.platform.dto.ProductDTO;
import com.pet.platform.entity.Product;
import com.pet.platform.exception.BusinessException;
import com.pet.platform.mapper.ProductMapper;
import com.pet.platform.service.ProductService;
import com.pet.platform.util.FileUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Autowired
    private FileUtil fileUtil;

    @Override
    public Product findById(Long id) {
        return productMapper.findById(id)
            .orElseThrow(() -> new BusinessException("商品不存在"));
    }

    @Override
    @Transactional(readOnly = true)
    public PageResult<ProductDTO> findPage(Integer pageNum, Integer pageSize, String keyword, String category) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("offset", (pageNum - 1) * pageSize);
            params.put("pageSize", pageSize);
            if (keyword != null && !keyword.isEmpty()) {
                params.put("keyword", keyword);
            }
            if (category != null && !category.isEmpty()) {
                params.put("category", category);
            }

            List<Product> products = productMapper.findList(params);
            if (products == null) {
                products = new ArrayList<>();
            }
            Long total = productMapper.count(params);

            List<ProductDTO> productDTOs = products.stream()
                    .map(this::convertToDTO)
                    .collect(Collectors.toList());

            return new PageResult<>(productDTOs, total, pageNum, pageSize);
        } catch (Exception e) {
            throw new BusinessException("获取商品列表失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(ProductDTO productDTO) {
        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);
        product.setSales(0);
        product.setStatus(1); // 设置默认状态为1（正常）
        productMapper.insert(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Long id, ProductDTO productDTO) {
        Product existingProduct = productMapper.findById(id)
            .orElseThrow(() -> new BusinessException("商品不存在"));

        Product product = new Product();
        BeanUtils.copyProperties(productDTO, product);
        product.setId(id);
        productMapper.update(product);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Product existingProduct = productMapper.findById(id)
            .orElseThrow(() -> new BusinessException("商品不存在"));

        // 删除商品图片
        if (existingProduct.getImageUrl() != null) {
            fileUtil.deleteFile(existingProduct.getImageUrl());
        }

        productMapper.delete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadImage(Long id, MultipartFile file) {
        Product existingProduct = productMapper.findById(id)
            .orElseThrow(() -> new BusinessException("商品不存在"));

        // 删除旧图片
        if (existingProduct.getImageUrl() != null) {
            fileUtil.deleteFile(existingProduct.getImageUrl());
        }

        // 上传新图片
        String imageUrl = fileUtil.uploadFile(file, "product");

        // 更新商品图片URL
        Product product = new Product();
        product.setId(id);
        product.setImageUrl(imageUrl);
        productMapper.update(product);

        return imageUrl;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStock(Long id, Integer stock) {
        Product existingProduct = productMapper.findById(id)
            .orElseThrow(() -> new BusinessException("商品不存在"));

        if (stock < 0) {
            throw new BusinessException("库存不能小于0");
        }

        existingProduct.setStock(stock);
        productMapper.updateStock(existingProduct);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSales(Long id, Integer increment) {
        Product existingProduct = productMapper.findById(id)
            .orElseThrow(() -> new BusinessException("商品不存在"));

        productMapper.updateSales(id, increment);
    }

    private ProductDTO convertToDTO(Product product) {
        ProductDTO productDTO = new ProductDTO();
        BeanUtils.copyProperties(product, productDTO);
        return productDTO;
    }
} 